package main

import (
	"bufio"
	"fmt"
	"io"
	"log"
	"os"
	"os/exec"
	"path"
	"strings"
)

func main1() {
	//root := `/root/movie1/水月洞天`
	//root := `/root/movie1/灵镜传奇`
	root := `/Users/showurl/Desktop/水月洞天2`
	newRoot := `/Users/showurl/Desktop/水月洞天3`
	readDir, err := os.ReadDir(root)
	if err != nil {
		panic(err)
	}
	for _, entry := range readDir {
		if !entry.IsDir() {
			continue
		}
		subDirName := entry.Name()
		subDirPath := path.Join(root, subDirName)
		subDir, err := os.ReadDir(subDirPath)
		if err != nil {
			panic(err)
		}
		for _, fileEntry := range subDir {
			if fileEntry.IsDir() {
				continue
			}
			filename := fileEntry.Name()
			if strings.HasSuffix(filename, ".mp4") {
				newDirPath := path.Join(newRoot, subDirName)
				_ = os.MkdirAll(newDirPath, 0777)
				newPath := path.Join(newDirPath, filename)
				_ = os.RemoveAll(newPath)
				cmd(path.Join(subDirPath, filename), newPath, strings.TrimSuffix(filename, ".mp4"))
			}
		}
	}
}
func main() {
	playlist, err := os.ReadFile("../playlist.txt")
	if err != nil {
		panic(err)
	}
	files := strings.Split(string(playlist), "\n")
	for i, file := range files {
		filePath := strings.TrimSuffix(strings.TrimPrefix(file, `file '`), "'")
		split := strings.Split(filePath, "/")
		filename := split[len(split)-1]
		fmt.Printf("%s\n", filePath)
		if i == 0 {
			err = Command(exec.Command("scp", "root@192.168.2.218:"+filePath, "."))
			if err != nil {
				panic(err)
			}
		}
		go func() {
			for i, s := range files {
				if i == 0 {
					continue
				}
				filePath := strings.TrimSuffix(strings.TrimPrefix(s, `file '`), "'")
				err = Command(exec.Command("scp", "root@192.168.2.218:"+filePath, "."))
				if err != nil {
					panic(err)
				}
			}
		}()
		newDirPath := []string{split[0], split[1], split[2] + "1"}
		cmd(filename, "output/"+filename, strings.TrimSuffix(filename, ".mp4"))
		go func() {
			err = Command(exec.Command("scp", "output/"+filename, "root@192.168.2.218:"+path.Join(newDirPath...)))
			if err != nil {
				panic(err)
			}
			os.Remove(filename)
			os.Remove("output/"+filename)
		}()
	}
}

func cmd(origin string, newPath string, text string) {
	cmd := `ffmpeg -re -i "%s" -vf "drawtext=fontfile='/root/Arial Unicode.ttf': text='%s':x=17:y=542:fontsize=17:fontcolor=white:shadowy=2" -vcodec libx264 -acodec copy -f mp4 "%s"`
	err := Command(exec.Command("sh", "-c", fmt.Sprintf(cmd, origin, text, newPath)))
	if err != nil {
		panic(err)
		log.Println(err.Error())
	}
}

func Command(c *exec.Cmd) error {
	log.Println("执行命令: ", strings.Join(c.Args, " "))
	stdout, err := c.StdoutPipe()
	if err != nil {
		return err
	}
	go func() {
		reader := bufio.NewReader(stdout)
		for {
			readString, err := reader.ReadString('\n')
			if err != nil || err == io.EOF {
				break
			}
			log.Print(readString)
		}
	}()
	return c.Run()
}
